

/*
GlobalKey 获取子组件:
globalKey.currentState 可以获取子组件的状态，
执行子组件的方法，globalKey.currentWidget可以获
取子组件的属性，_globalKey.currentContext!.findRenderObject()可以获取渲染的属性。
 */


import 'package:flutter/material.dart';

class GlobalKeyGetAttribute extends StatefulWidget {
  const GlobalKeyGetAttribute({super.key});
  @override
  State<GlobalKeyGetAttribute> createState() => _HomePageState();
}
class _HomePageState extends State<GlobalKeyGetAttribute> {
  final GlobalKey _globalKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: (){
//1、获取子组件的状态 调用子组件的属性
          var state=(_globalKey.currentState as _BoxState);
              setState(() {
              state._count++;
          });
//2、获取子组件的属性
          var box=(_globalKey.currentWidget as Box);
          print(box.color);
//3、获取子组件渲染的属性
          var renderBox= (_globalKey.currentContext!.findRenderObject() as
          RenderBox);
          print(renderBox.size);
        },
      ),
      appBar: AppBar(
        title: const Text('Title'),
      ),
      body: Center(
        child: Box(
          key: _globalKey,
          color: Colors.red,
        ),
      ),
    );
  }
}
class Box extends StatefulWidget {
  final Color color;
  const Box({Key? key, required this.color}):super(key: key);
  @override
  State<Box> createState() => _BoxState();
}
class _BoxState extends State<Box> {
  int _count = 0;
  run(){
    print("run");
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 100,
      width: 100,
      child: ElevatedButton(
        style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(widget.color)),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Center(
          child: Text("$_count"),
        ),
      ),
    );
  }
}